package com.rankeiot.ai.controller;

import com.rankeiot.ai.domain.FunctionEntity;

import lombok.RequiredArgsConstructor;

import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.inner.argumet.QueryPage;
import com.rankeiot.core.util.CollectionUtil;
import org.sagacity.sqltoy.dao.LightDao;
import org.sagacity.sqltoy.model.Page;
import com.rankeiot.core.data.response.Resp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.rankeiot.ai.AiMenu;
import com.rankeiot.core.sqltoy.Sql;


import jakarta.validation.Valid;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.ssssssss.magicapi.function.service.FunctionMagicDynamicRegistry;

import java.util.List;

/**
* AI功能调用
*/
@Tag(name="AI功能调用")
@Auth(AiMenu.APPLICATION)
@RestController
@RequestMapping("function")
@RequiredArgsConstructor
public class FunctionController{

    final LightDao dao;
    final FunctionMagicDynamicRegistry functions;
    final MagicAPIService magicAPIService;
    /**
    * 新增AI功能调用
    */
    @Operation(summary="新增AI功能调用")
    @PostMapping("add")
    public Resp add(@Valid @RequestBody FunctionEntity function){
        dao.save(function);
        return Resp.ok();
    }

    /**
    * 删除AI功能调用
    */
    @Operation(summary="删除AI功能调用")
    @Transactional
    @PostMapping("delete")
    public Resp delete(List<Long> ids){
        // dao.loadAll(functions);
        List<FunctionEntity> functions = CollectionUtil.map(ids, FunctionEntity::new);
        dao.deleteAll(functions);
        return Resp.ok();
    }

    /**
    * 更新AI功能调用
    */
    @Operation(summary="更新AI功能调用")
    @PostMapping("save")
    public Resp save(@Valid @RequestBody FunctionEntity function){
        dao.update(function);
        return Resp.ok();
    }

    /**
    *  获取AI功能调用
    */
    @Operation(summary="获取AI功能调用详细")
    @GetMapping("detail")
    public Resp<FunctionEntity> detail(Long id){
       FunctionEntity function=dao.load(new FunctionEntity(id));
       return Resp.of(function);
    }
    /**
    * 获取AI功能调用列表
    */
    @Operation(summary="列出AI功能调用")
    @PostMapping("list")
    public Resp<FunctionEntity> list(QueryPage query){
        String sql=Sql.select("id,name,description,direct,script,per_script")
                .from(FunctionEntity.TABLE)
                .eq(FunctionEntity.Fields.appId)
                .optional(q -> q
                    .eq(FunctionEntity.Fields.name)
                    .eq(FunctionEntity.Fields.description)
                ).orderByDesc(FunctionEntity.Fields.id)
                .toString();
        Page result = dao.findPage(query.page(),sql,query.params(), FunctionEntity.class);
        return Resp.of(result);
    }

    @GetMapping("fun_infos")
    public Resp getFunctions(){
      return Resp.of( functions.mappings().stream().distinct().toList());
    }
}
